import {Action} from '@flow-step/step-toolkit/lib/interaction'
import * as step from '@flow-step/step-toolkit'
import {Sae, SaeInterface} from './sae'
import {DescribeChangeOrderRequest, DescribeChangeOrderResponse} from '@alicloud/sae20190506'
import {printJSON} from './utils'
import {IParams} from './params'

export async function check(params:IParams, sae: SaeInterface) {
    if (!params.CHANGE_ORDER_ID) {
        throw new Error('CHANGE_ORDER_ID is not set in environment variables');
    }
    step.info(`CHECKING THE STATUS OF THE DEPLOYMENT TASK ${params.CHANGE_ORDER_ID}`)

    const request = new DescribeChangeOrderRequest({
        changeOrderId: params.CHANGE_ORDER_ID
    })
    let response: DescribeChangeOrderResponse
    try {
        response = await sae.describeChangeOrder(request)
    }catch (error){
        throw new Error(`failed to get application config: ${error}`)
    }
    if (response.body?.code != '200'){
        throw new Error(`check deployment failed, code: ${response.body?.code}, message: ${response.body?.message}`)
    }
    const result = response.body?.data
    if (result == undefined){
        throw new Error("check deployment failed, result is empty")
    }
    const nextPipelineId = await sae.getNextPipelineID(result)
    if (nextPipelineId != undefined){
        step.exportEnvVar("NEXT_PIPELINE_ID", nextPipelineId)
    }
    const formattedResult = {
        ChangeOrderId: result.changeOrderId,
        Status: result.status,
        NextPipelineId: nextPipelineId
    };

    step.info("[USER]result")
    printJSON(formattedResult)

    const status = result.status
    step.info(`[USER]deployment status: ${status}`)


    step.addOutput(`APP_NAME=${params.APP_NAME}`)
    step.addOutput(`CHANGE_ORDER_ID=${params.CHANGE_ORDER_ID}`)
    step.addOutput(`GLOBAL_CANCEL_HOOK_ACTION=TERMINATE`)
    step.addOutput(`GLOBAL_CHANGE_ORDER_ID=${params.CHANGE_ORDER_ID}`)
    step.interaction.addLink("发布单详情", `https://saenext.console.aliyun.com/${params.regionID}/app-list/${params.APPLICATION_ID}/micro-app/record/${params.CHANGE_ORDER_ID}`,41)

    step.info(`[USER]APP_NAME=${params.APP_NAME}`)
    step.info(`CHANGE_ORDER_ID=${params.CHANGE_ORDER_ID}`)

    switch (status) {
        case 0:
            step.info("[USER]The change order is being prepared.")
            step.interaction.runAction('CHECK')
            break
        case 1:
            step.info("[USER]The change order is being executed.")
            step.interaction.runAction('CHECK')
            break
        case 2:
            step.info("[USER]The change order is executed successfully.")
            step.addOutput("RERUNABLE=true")
            break
        case 3:
            throw new Error("[USER]The change order could not be executed. Check SAE console for details.")
        case 6:
            throw new Error("[USER]The change order was terminated. Check SAE console for details.")
        case 9:
            step.info("[USER]The execution process is pending. SAE will automatically determine the release batches.")
            step.interaction.runAction('CHECK')
            break
        case 10:
            throw new Error("[USER]The execution failed due to a system exception. Check SAE console for details.")
        case 11:
            step.info("[USER]The change order is pending approval. Check SAE console for details.")
            step.interaction.runAction('CHECK')
            break
        case 12:
            step.info("[USER]The change order is approved and is pending execution.")
            step.interaction.runAction('CHECK')
            break
        case 8:
            if (nextPipelineId == undefined){
                throw new Error("next pipeline id is empty")
            }
            step.info("[USER]The execution process is pending. You must manually determine the release batch.")
            step.addOutput(`NEXT_PIPELINE_ID=${nextPipelineId}`)
            step.info(`[USER]NEXT_PIPELINE_ID=${nextPipelineId}`)

            const actions: Action[] = [
                {
                    type: "EXECUTE",
                    name: params.domestic? "继续发布": "Continue Deployment",
                    order : 42,
                    hidden: false,
                    action: "CONFIRM"
                },
                {
                    type: "EXECUTE",
                    name: params.domestic? "回退发布": "rollback Deployment",
                    order : 43,
                    hidden: false,
                    action: "ROLLBACK",
                }
            ]
            step.interaction.appendActions(actions)
            break
        default:
            throw new Error(`[USER]The execution status is unknown: ${status}`)
    }
}
